package com.muqi.app.qlearn.mine;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.muqi.app.afinalcache.ACache;
import com.muqi.app.network.http.AsyncCacheHttpForGet.LoadOverListener;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.network.http.AsyncCacheHttpForGet;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.AppUtils;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.modles.AddressBean;
import com.muqi.app.qlearn.student.BaseFragmentActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.user.address.CitycodeUtil;
import com.muqi.app.user.address.Cityinfo;
import com.muqi.app.user.address.SelectAddressWindow;
import com.muqi.app.user.address.SelectAddressWindow.OnConfirmSelectListener;

public class AddressNewActivity extends BaseFragmentActivity implements OnClickListener, 
	OnCheckedChangeListener, OnConfirmSelectListener, LoadOverListener {
	
	public static final String ADDRESSDATA = "address_bean";
	private Button saveAddress;
	private EditText name;
	private EditText phoneNum;
	private TextView address;
	private EditText addrDetail;
	private EditText mailCode;
	private CheckBox checkBox;

	private AddressBean data;
	private String addressId = "";
	private String provinceId = "";
	private String cityId = "";
	private String districtId = "";
	private String checked = "0";
	private SelectAddressWindow addressWindow = null;
	private static List<Cityinfo> province_list = new ArrayList<Cityinfo>();
	private ACache mcache;
	private String[] ids;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aty_create_new_address);
	}

	@Override
	protected void onInit() {
		saveAddress = (Button) findViewById(R.id.saveAddress);
		name = (EditText) findViewById(R.id.edit_addr_name_input);
		phoneNum = (EditText) findViewById(R.id.edit_addr_phone_input);
		address = (TextView) findViewById(R.id.edit_addr_area_input);
		addrDetail = (EditText) findViewById(R.id.edit_addr_detail_input);
		mailCode = (EditText) findViewById(R.id.edit_addr_mailcode_input);
		checkBox = (CheckBox) findViewById(R.id.set_default);
		address.setOnClickListener(this);
		saveAddress.setOnClickListener(this);
		checkBox.setOnCheckedChangeListener(this);
	}

	@Override
	protected void onData() {
		data = (AddressBean) getIntent().getSerializableExtra(ADDRESSDATA);
		if (data != null) {
			addressId = data.getDizhi_id();
			provinceId = data.getProvince_id();
			cityId = data.getCity_id();
			districtId = data.getDistrict_id();

			name.setText(data.getLianxiren());
			phoneNum.setText(data.getLianxidianhua());
			address.setText(data.getProvince_name() + " " + data.getCity_name()
					+ " " + data.getDistrict_name());

			addrDetail.setText(data.getDizhi());

			if (TextUtils.equals(data.getChangyong(), "1")) {
				checkBox.setChecked(true);
			} else {
				checkBox.setChecked(false);
			}
		}

		initAddressWidow();
	}

	private void initAddressWidow() {
		
		mcache = ACache.get(this);
		String cacheJson = mcache.getAsString("goods/dizhi/get_all_province_city_district/");
		
		if(cacheJson == null || TextUtils.isEmpty(cacheJson)){
			loadingCitys();
		}else{
			province_list = CitycodeUtil.getCitys(this, cacheJson);
			if (province_list != null && province_list.size() > 0) {
				addressWindow = new SelectAddressWindow(this, province_list,this,3);
			}else{
				loadingCitys();
			}
		}
	}
	
	private void loadingCitys() {
		AsyncCacheHttpForGet.getInstance(this);
		AsyncCacheHttpForGet.getCacheHttp("goods/dizhi/get_all_province_city_district/", this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.saveAddress:
			if (checkOk()) {
				v.setEnabled(false);
				saveAddress(v);
			}
			break;
		case R.id.edit_addr_area_input:
			if (addressWindow != null) {
				addressWindow.showAsDropDown(v);
			} else {
				initAddressWidow();
			}
			break;

		default:
			break;
		}
	}

	private void saveAddress(final View v) {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("token", mSpUtil.getToken());
			params.put("dizhi_id", addressId);
			params.put("province_id", provinceId);
			params.put("city_id", cityId);
			params.put("district_id", districtId);
			params.put("lianxiren", name.getText().toString().trim());
			params.put("lianxidianhua", phoneNum.getText().toString().trim());
			params.put("dizhi", addrDetail.getText().toString().trim());
			params.put("youbian", "");
			params.put("changyong", checked);
			String requestApi = ParamsUtils.buildParams(NetWorkApi.CREATE_USER_ADDRESS_API, params);
			MyAsyncHttp.get(this, requestApi, new AsyncCallBackListener() {
				
				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode, String request,
						String result) {
					v.setEnabled(true);
					if(resuleCode == RESULTCODE.SUCCESS){
						showToast("保存成功");
						Intent intent = new Intent();
						AddressNewActivity.this.setResult(RESULT_OK, intent);
						finish();
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);
		}
	}

	
	private boolean checkOk() {
		boolean isOk = true;
		if ("".equals(name.getText().toString().trim())) {
			isOk = false;
			showToast("姓名不能为空");
			// name.setError("姓名不能为空");
		} else if ("".equals(phoneNum.getText().toString().trim())) {
			isOk = false;
			showToast("手机号不能为空");
			// phoneNum.setError("手机号不能为空");
		} else if (!AppUtils.checkPhone(phoneNum.getText().toString().trim())) {
			isOk = false;
			showToast("手机号不正确");
			// phoneNum.setError("手机号不正确");
		} else if ("".equals(address.getText().toString().trim())) {
			isOk = false;
			showToast("所在区域不能为空");
			// address.setError("所在区域不能为空");
		} else if ("".equals(addrDetail.getText().toString().trim())) {
			isOk = false;
			showToast("详细地址不能为空");
			// addrDetail.setError("详细地址不能为空");
		}
		return isOk;
	}

	public void finish(View view) {
		finish();
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			checked = "1";
		} else {
			checked = "0";
		}
	}


	@Override
	public void onConfirmSelect(String data, String id) {
		ids = id.split(",");
		if (province_list.get(Integer.valueOf(ids[0])) != null) {
			provinceId = province_list.get(Integer.valueOf(ids[0])).getId();
			if (province_list.get(Integer.valueOf(ids[0])).getCityInfos()
					.get(Integer.valueOf(ids[1])) != null) {
				cityId = province_list.get(Integer.valueOf(ids[0]))
						.getCityInfos().get(Integer.valueOf(ids[1])).getId();
				if (province_list.get(Integer.valueOf(ids[0])).getCityInfos()
						.get(Integer.valueOf(ids[1])).getCityInfos() != null
						&& province_list.get(Integer.valueOf(ids[0]))
								.getCityInfos().get(Integer.valueOf(ids[1]))
								.getCityInfos().size() > 0) {
					
					districtId = province_list.get(Integer.valueOf(ids[0]))
							.getCityInfos().get(Integer.valueOf(ids[1]))
							.getCityInfos().get(Integer.valueOf(ids[2]))
							.getId();
				}
			}
		}
		address.setText(data);
	}

	@Override
	public void onOverResult(String request, String result) {
		province_list = CitycodeUtil.getCitys(this, result);
		if (province_list != null && province_list.size() > 0) {
			addressWindow = new SelectAddressWindow(this, province_list,this,3);
		}else{
			showToast("城市列表为空");
		}
		
	}
}
